import React, { useState, useEffect } from 'react';
import './Userinfo.css';
import Bottom from '../components/bottom/Bottom';
import { Top } from '../components/top/Top';
import { accountService } from '../../service/accountService';
import { common_utils } from '../../utils/utils';
import { debounce } from 'lodash';

const MyAccount = () => {
  const [user, setUser] = useState(null);
  const [account, setAccount] = useState({
    userid: 1,
    firstname: '',
    lastname: '',
    email: '',
    phone: '',
    addr1: '',
    addr2: '',
    city: '',
    state: '',
    zip: 1,
    country: '',
    username: '',
    password: '',
  });
  const [usernameTips, setUsernameTips] = useState('');
  const [usernameClass, setUsernameClass] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [imageFile, setImageFile] = useState(null);

  const updateAccountState = (data) => {
    setAccount({
      userid: data.userid,
      firstname: data.firstname,
      lastname: data.lastname,
      email: data.email,
      phone: data.phone,
      addr1: data.addr1,
      addr2: data.addr2,
      city: data.city,
      state: data.state ,
      zip: data.zip,
      country: data.country,
      username: data.username,
      password: data.password,
    });
  };

  useEffect(() => {
    const storedUser = JSON.parse(localStorage.getItem('user'));
    if (storedUser) {
      setUser(storedUser);
      accountService.accountInfo(storedUser.username, (response) => {
        if (response.code === 1000) {
          updateAccountState(response.data);
          
        } else {
          alert('Failed to fetch account data');
          
        }
      });
    } else {
      
    }
  }, []);

 
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setAccount((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setImageFile(file);
    }
  };

  const debouncedCheckUsername = debounce((username) => {
    accountService.checkUsername(username).then((response) => {
      if (response.available) {
        setUsernameTips('Username is available');
        setUsernameClass('okTips');
      } else {
        setUsernameTips('Username is taken');
        setUsernameClass('errorTips');
      }
    });
  }, 300);

  const handleUsernameBlur = () => {
    if (!isEditing || !account.username) return;
    debouncedCheckUsername(account.username);
  };

  const handleEdit = (e) => {
    e.preventDefault();
    setIsEditing(true);
  };

  const handleSave = (e) => {
    e.preventDefault();
    // const formData = new FormData();
    // formData.append('account', JSON.stringify({
    //   ...account,
    //   addr1: account.address1,
    //   addr2: account.address2,
    // }));
    // if (imageFile) {
    //   formData.append('image', imageFile);
    // }

    accountService.updateAccount(common_utils.getUsername(), account, (response) => {

     
      if (response.code === 1000) {
        alert('Account updated successfully');
        setIsEditing(false);
      } else {
        alert('Failed to update account');
      }
    });
  };

  const handleCancel = (e) => {
    e.preventDefault();
    setIsEditing(false);
    setImageFile(null);
    if (user) {
      accountService.accountInfo(user.username, (response) => {
        if (response.code === 1000) {
          updateAccountState(response.data);
        } else {
          alert('Failed to fetch account data');
        }
      });
    }
  };

  const handleDelete = (e) => {
    e.preventDefault();
    if (!user?.username) {
      alert('No user found');
      return;
    }
    if (window.confirm('Are you sure you want to delete your account? This cannot be undone.')) {
      accountService.deleteAccount(user.username, (response) => {
        if (response.code === 1000) {
          alert('Account deleted successfully');
          accountService.logout();
          common_utils.toLogin();
          
        } else {
          alert('Failed to delete account');
        }
      });
    }
  };

  return (
    <div className="page-wrapper user-info-page">
      <Top />
      <main className="user-info-container">
        <div className="user-info-card">
          <h2 className="user-info-title">My Account</h2>

          <form className="user-info-form" onSubmit={handleSave}>
            <fieldset className="form-section">
              <legend className="section-title">Profile Information</legend>
              <div className="form-grid">
                <div className="form-groupp">
                  <label htmlFor="userImage">Profile Image</label>
                  <div className="user-image-container">
                    {user?.image ? (
                      <img
                        src={common_utils.getServerImageURL(user.image)}
                        alt="User profile"
                        className="user-image"
                      />
                    ) : (
                      <div className="user-image-placeholder">No Image</div>
                    )}
                    {isEditing && (
                      <input
                        type="file"
                        id="userImage"
                        name="userImage"
                        accept="image/*"
                        onChange={handleImageChange}
                        disabled={!isEditing}
                      />
                    )}
                  </div>
                </div>
                <div className="form-groupp">
                  <label htmlFor="firstname">First Name *</label>
                  <input
                    type="text"
                    id="firstname"
                    name="firstname"
                    value={account.firstname}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    required
                    aria-required="true"
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="lastname">Last Name *</label>
                  <input
                    type="text"
                    id="lastname"
                    name="lastname"
                    value={account.lastname}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    required
                    aria-required="true"
                  />
                </div>
              </div>
            </fieldset>

            <fieldset className="form-section">
              <legend className="section-title">Contact Information</legend>
              <div className="form-grid">
                <div className="form-groupp">
                  <label htmlFor="email">Email *</label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={account.email}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    required
                    aria-required="true"
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="phone">Phone</label>
                  <input
                    type="tel"
                    id="phone"
                    name="phone"
                    value={account.phone}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
              </div>
            </fieldset>

            <fieldset className="form-section">
              <legend className="section-title">Address</legend>
              <div className="form-grid">
                <div className="form-groupp">
                  <label htmlFor="address1">Address Line 1</label>
                  <input
                    type="text"
                    id="address1"
                    name="address1"
                    value={account.addr1}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="address2">Address Line 2</label>
                  <input
                    type="text"
                    id="address2"
                    name="address2"
                    value={account.addr2}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="city">City</label>
                  <input
                    type="text"
                    id="city"
                    name="city"
                    value={account.city}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="state">State/Province</label>
                  <input
                    type="text"
                    id="state"
                    name="state"
                    value={account.state}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="zip">ZIP/Postal Code</label>
                  <input
                    type="text"
                    id="zip"
                    name="zip"
                    value={account.zip}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
                <div className="form-groupp">
                  <label htmlFor="country">Country</label>
                  <input
                    type="text"
                    id="country"
                    name="country"
                    value={account.country}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                  />
                </div>
              </div>
            </fieldset>

            <fieldset className="form-section">
              <legend className="section-title">Account Credentials</legend>
              <div className="form-grid">
                <div className="form-groupp">
                  <label htmlFor="username">Username *</label>
                  <input
                    type="text"
                    id="username"
                    name="username"
                    value={account.username}
                    onChange={handleInputChange}
                    onBlur={handleUsernameBlur}
                    disabled={!isEditing}
                    required
                    aria-required="true"
                  />
                  <span className={`username-feedback ${usernameClass}`}>{usernameTips}</span>
                </div>
                <div className="form-groupp">
                  <label htmlFor="password">Password *</label>
                  <input
                    type="password"
                    id="password"
                    name="password"
                    value={account.password}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    required
                    aria-required="true"
                  />
                </div>
              </div>
            </fieldset>

            <div className="form-actions">
              {!isEditing ? (
                <button
                  className="edit-btn"
                  onClick={handleEdit}
                  aria-label="Edit account information"
                >
                  Edit Profile
                </button>
              ) : (
                <>
                  <button type="submit" className="save-btn" aria-label="Save account changes">
                    Save Changes
                  </button>
                  <button
                    className="cancel-btn"
                    onClick={handleCancel}
                    aria-label="Cancel editing"
                  >
                    Cancel
                  </button>
                </>
              )}
              <button
                className="delete-btn"
                onClick={handleDelete}
                aria-label="Delete account"
              >
                Delete Account
              </button>
            </div>
          </form>
        </div>
      </main>
      <Bottom />
    </div>
  );
};

export default MyAccount;